import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/models/learning_record.dart';
import '../../shared/models/word.dart';
import '../../shared/providers/word_provider.dart';
import '../../shared/providers/vocabulary_learning_provider.dart';
import '../../data/master_vocabulary.dart';

// 使用可刷新的学习记录Provider
final learningRecordsProvider = refreshableRecordsProvider;

class LearningRecordsPage extends ConsumerWidget {
  const LearningRecordsPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final recordsAsync = ref.watch(learningRecordsProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('Learning Records'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.green,
                Colors.green.shade600,
              ],
            ),
          ),
        ),
        leading: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: IconButton(
            icon: const FaIcon(
              FontAwesomeIcons.arrowLeft,
              color: Colors.white,
              size: 18,
            ),
            onPressed: () => Navigator.pop(context),
          ),
        ),
        actions: [
          Container(
            margin: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: IconButton(
              icon: const FaIcon(
                FontAwesomeIcons.arrowsRotate,
                color: Colors.white70,
                size: 18,
              ),
              onPressed: () {
                // 手动刷新记录
                ref.read(refreshTriggerProvider.notifier).state++;
              },
            ),
          ),
        ],
      ),
      body: recordsAsync.when(
        data: (records) => _buildRecordsList(context, records),
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, stack) => _buildError(error.toString()),
      ),
    );
  }

  Widget _buildRecordsList(BuildContext context, List<LearningRecord> records) {
    if (records.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.history,
              size: 64,
              color: Colors.grey,
            ),
            SizedBox(height: 16),
            Text(
              'No learning records yet',
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
            ),
            SizedBox(height: 8),
            Text(
              'Complete some quizzes to see your progress here',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      );
    }

    // Calculate statistics
    final totalQuestions = records.length;
    final correctAnswers = records.where((r) => r.isCorrect).length;
    final accuracy = totalQuestions > 0 ? (correctAnswers / totalQuestions * 100) : 0.0;

    // Sort records by time (most recent first)
    records.sort((a, b) => b.studiedAt.compareTo(a.studiedAt));

    // Group records by date
    final groupedRecords = <String, List<LearningRecord>>{};
    for (final record in records) {
      final dateKey = _formatDate(record.studiedAt);
      groupedRecords[dateKey] = groupedRecords[dateKey] ?? [];
      groupedRecords[dateKey]!.add(record);
    }

    final sortedDates = groupedRecords.keys.toList()
      ..sort((a, b) => b.compareTo(a)); // Most recent first

    // Sort records within each date group (most recent first)
    for (final dateKey in groupedRecords.keys) {
      groupedRecords[dateKey]!.sort((a, b) => b.studiedAt.compareTo(a.studiedAt));
    }

    return Column(
      children: [
        _buildStatsCard(totalQuestions, correctAnswers, accuracy),
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: sortedDates.length,
            itemBuilder: (context, index) {
              final date = sortedDates[index];
              final dayRecords = groupedRecords[date]!;
              return _buildDateSection(date, dayRecords);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildStatsCard(int total, int correct, double accuracy) {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.green.shade50,
            Colors.green.shade100,
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.green.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem(
            'Total',
            total.toString(),
            Icons.quiz,
            Colors.blue,
          ),
          _buildStatItem(
            'Correct',
            correct.toString(),
            Icons.check_circle,
            Colors.green,
          ),
          _buildStatItem(
            'Accuracy',
            '${accuracy.toStringAsFixed(1)}%',
            Icons.analytics,
            Colors.orange,
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon, Color color) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
          child: Icon(
            icon,
            color: color,
            size: 20,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          value,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  Widget _buildDateSection(String date, List<LearningRecord> records) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 8),
          child: Text(
            date,
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: AppConstants.DARK_BLUE,
            ),
          ),
        ),
        ...records.map((record) => _buildRecordCard(record)).toList(),
        const SizedBox(height: 16),
      ],
    );
  }

  Widget _buildRecordCard(LearningRecord record) {
    // 根据wordId查找对应的词汇
    final word = MasterVocabulary.allVocabulary.firstWhere(
      (w) => w.id == record.wordId,
      orElse: () => Word(
        id: record.wordId,
        esperanto: 'Unknown',
        english: 'Unknown',
        pronunciation: 'Unknown',
        definition: 'Word not found',
        examples: [],
        category: 'Unknown',
        audioUrl: '',
        difficulty: 1,
      ),
    );

    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: ListTile(
        leading: Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: record.isCorrect 
                ? Colors.green.withOpacity(0.1)
                : Colors.red.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
          child: Icon(
            record.isCorrect ? Icons.check : Icons.close,
            color: record.isCorrect ? Colors.green : Colors.red,
          ),
        ),
        title: Text(
          '${word.esperanto} → ${word.english}',
          style: const TextStyle(
            fontWeight: FontWeight.w500,
          ),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              word.definition,
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(height: 2),
            Row(
              children: [
                Text(
                  'Category: ${word.category}',
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[500],
                  ),
                ),
                const SizedBox(width: 8),
                Text(
                  'Level: ${record.difficulty}',
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[500],
                  ),
                ),
                const Spacer(),
                Text(
                  _formatTime(record.studiedAt),
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[500],
                  ),
                ),
              ],
            ),
          ],
        ),
        trailing: Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: record.isCorrect 
                ? Colors.green.withOpacity(0.1)
                : Colors.red.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            record.isCorrect ? 'Correct' : 'Wrong',
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: record.isCorrect ? Colors.green : Colors.red,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildError(String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red,
          ),
          const SizedBox(height: 16),
          const Text(
            'Error loading records',
            style: TextStyle(
              fontSize: 18,
              color: Colors.red,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            error,
            style: const TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = now.difference(date).inDays;
    
    if (difference == 0) {
      return 'Today';
    } else if (difference == 1) {
      return 'Yesterday';
    } else {
      return '${date.day}/${date.month}/${date.year}';
    }
  }

  String _formatTime(DateTime date) {
    return '${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
  }
} 